package com.crm.service.purchaseService;

import com.crm.dao.client.ClientInfoDao;
import com.crm.dao.client.ContactDao;
import com.crm.dao.permission.UserInfoDAO;
import com.crm.dao.productionDAO.ProductionDetilsDAO;
import com.crm.dao.purchaseDAO.PurchaseDAO;
import com.crm.dao.purchaseDAO.PurchaseproductiondetailDAO;
import com.crm.pojo.*;
import com.crm.vo.PurchaseUserInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class)
public class PurchaseService {
    @Autowired
    private PurchaseDAO purchaseDAO;
    @Autowired
    private PurchaseproductiondetailDAO purchaseproductiondetailDAO;
    @Autowired
    private ClientInfoDao clientInfoDAO;
    @Autowired
    private UserInfoDAO userInfoDAO;
    @Autowired
    private ProductionDetilsDAO productionDetilsDAO;
    @Autowired
    private ContactDao contactDao;

    //模糊查询根据采购标题和采购id
    public List<Inandoutlog> findAllBymh(String q){
        List<Inandoutlog> l = new ArrayList<>();
        List<Purchase> list = purchaseDAO.findAllpurBymh("%"+q+"%");
        for (Purchase p: list) {
            Inandoutlog io =new Inandoutlog();
            io.setIoDispatherTitle(p.getPurtheme());
            io.setIoDispatherId(p.getPurid());
            l.add(io);
        }
        return l;
    }
    //查询所有采购单根据采购标题和采购id
    public List<Inandoutlog> findAllBymh2(){
        List<Inandoutlog> l = new ArrayList<>();
        List<Purchase> list = purchaseDAO.findAllpurBymhnone();
        for (Purchase p: list) {
            Inandoutlog io =new Inandoutlog();
            io.setIoDispatherTitle(p.getPurtheme());
            io.setIoDispatherId(p.getPurid());
            l.add(io);
        }
        return l;
    }
    //根据id查询单个采购单
    public Purchase findOneById(Long purchaseId){
        return purchaseDAO.findOne(purchaseId);
    }
    //保存采购单
    public void savePurchase(Purchase purchase){
        purchaseDAO.save(purchase);
    }
    //查询采购单的数量
    public Long queryCount(){
        return purchaseDAO.count();
    }
    //查询所有采购单
    public List<Purchase> allPurchasesPaged(int curPage, int pageSize){
        PageRequest page  = new PageRequest(curPage-1,pageSize);
        List<Purchase> purchases  = purchaseDAO.findAllByPaged(page);
        for (Purchase p:purchases) {
//            if(!purchaseproductiondetailDAO.findAllByPid(p.getPurid()).isEmpty()) {
//                List<Purchaseproductiondetail> purchaseproductiondetails = purchaseproductiondetailDAO.findAllByPid(p.getPurid());
//                for (Purchaseproductiondetail pdd:purchaseproductiondetails) {
//                    ProductionDetail productionDetail = productionDetilsDAO.findOne(pdd.getProid());
//                    pdd.setPpcost(pdd.getPpcount()*productionDetail.getPprice());
//                    p.setPurmoney(p.getPurmoney()+pdd.getPpcost());
//                }
//            }
            if(p.getContactId()!=null){
                if(contactDao.findOne(p.getContactId())!=null){
                    p.setClientname(contactDao.findOne(p.getContactId()).getClientInfo().getCname());
                }
            }
            if(p.getPurUserId()!=null){
                if(userInfoDAO.findOne(p.getPurUserId())!=null){
                    p.setPurUsername(userInfoDAO.findOne(p.getPurUserId()).getUrealName());
                }
            }
            if(p.getClientId()!=null){
                if(clientInfoDAO.findOne(p.getClientId())!=null){
                    p.setClientname(clientInfoDAO.findOne(p.getClientId()).getCname());
                }
            }
        }
        return purchases;
    }
    //模糊查询采购主题或经手人姓名
    public List<Purchase> getAllPurchasesBymh(String q){
        List<Purchase> plist  = new ArrayList<>();
        List<PurchaseUserInfoVO> vo = purchaseDAO.findAllpurBymh2("%"+q+"%");
        for(PurchaseUserInfoVO purchaseUserInfoVO:vo){
            purchaseUserInfoVO.getPurchase().setPurUsername(purchaseUserInfoVO.getUserinfo().getUrealName());
            plist.add(purchaseUserInfoVO.getPurchase());
        }
        for (Purchase p:plist) {
//            if(!purchaseproductiondetailDAO.findAllByPid(p.getPurpdid()).isEmpty()) {
//                List<Purchaseproductiondetail> purchaseproductiondetails = purchaseproductiondetailDAO.findAllByPid(p.getPurpdid());
//                for (Purchaseproductiondetail pdd:purchaseproductiondetails) {
//                    ProductionDetail productionDetail = productionDetilsDAO.findOne(pdd.getProid());
//                    pdd.setPpcost(pdd.getPpcount()*productionDetail.getPprice());
//                    p.setPurmoney(p.getPurmoney()+pdd.getPpcost());
//                }
//            }
            if(p.getContactId()!=null){
                if(contactDao.findOne(p.getContactId())!=null){
                    p.setClientname(contactDao.findOne(p.getContactId()).getClientInfo().getCname());
                }
            }
        }
        return plist;
    }
    //高级查询（多条件查询）
    public List<Purchase> proHlq(Purchase purchase, int currpage, int pagesize){
        Assert.notNull(purchase);
        PageRequest pageRequest = new PageRequest(currpage-1,pagesize);
        @SuppressWarnings("unchecked")
        Page<Purchase> result =  purchaseDAO.findAll(queryHl(purchase),pageRequest);
        List<Purchase> list = result.getContent();
        for (Purchase p:list) {
            if(p.getContactId()!=null){
                if(contactDao.findOne(p.getContactId())!=null){
                    p.setClientname(contactDao.findOne(p.getContactId()).getClientInfo().getCname());
                }
            }
            if(p.getPurUserId()!=null){
                if(userInfoDAO.findOne(p.getPurUserId())!=null){
                    p.setPurUsername(userInfoDAO.findOne(p.getPurUserId()).getUrealName());
                }
            }
            if(p.getClientId()!=null){
                if(clientInfoDAO.findOne(p.getClientId())!=null){
                    p.setClientname(clientInfoDAO.findOne(p.getClientId()).getCname());
                }
            }
        }
        return list;
    }
    //高级查询（总数）
    public Long proHlqCount(Purchase purchase){
        Assert.notNull((purchase));
        @SuppressWarnings("unchecked")
        Long count =purchaseDAO.count(queryHl(purchase));
        return count;
    }

    //高级查询产品信息(添加条件)
    public static Specification<Purchase> queryHl(Purchase purchase){
        return new Specification<Purchase>() {
            @Override
            public Predicate toPredicate(Root<Purchase> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //创建条件集合
                List<Predicate> list = new ArrayList<>();
                //添加条件
                if(!StringUtils.isEmpty(purchase.getPurtheme())){
                    list.add(criteriaBuilder.like(root.get("purtheme").as(String.class),"%"+purchase.getPurtheme()+"%"));
                }
                if(purchase.getClientId()!=null){
                    list.add(criteriaBuilder.equal(root.get("clientId").as(Long.class),purchase.getClientId()));
                }
                if(purchase.getContactId()!=null){
                    list.add(criteriaBuilder.equal(root.get("contactId").as(Long.class),purchase.getContactId()));
                }
                if(purchase.getPurUserId()!=null){
                    list.add(criteriaBuilder.equal(root.get("purUserId").as(Long.class),purchase.getPurUserId()));
                }
                if(purchase.getStartpurdate()!=null){
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("purdate").as(Date.class),purchase.getStartpurdate()));
                }
                if(purchase.getEndpurdate()!=null){
                    list.add(criteriaBuilder.lessThanOrEqualTo(root.get("purdate").as(Date.class),purchase.getEndpurdate()));
                }
                if(purchase.getStartpurexcepttime()!=null){
                    list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("purexcepttime").as(Date.class),purchase.getStartpurexcepttime()));
                }
                if(purchase.getEndpurexcepttime()!=null){
                    list.add(criteriaBuilder.lessThanOrEqualTo(root.get("purexcepttime").as(Date.class),purchase.getEndpurexcepttime()));
                }
                    list.add(criteriaBuilder.equal(root.get("purchaseIsDel").as(String.class),"否"));
                Predicate[] predicates = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(predicates));
            }
        };
    }
    //模糊查询采购标题
    public List<Purchase> findAllBythememh(String q){
        return purchaseDAO.findAllpurBythemeMh("%"+q+"%");
    }

    //接口 通过供应商/客户id 获取采购单以及采购产品明细
    public List<Purchase> getPurchasesByClientId(Long cid){
        return purchaseDAO.findAllByClientId(cid);
    }
}
